$(function ()
{
    //校验
    $("#loginForm").validate({
        rules : {
            account : "required",
            password : "required"
        },
        messages : {
            account : "请输入账号!",
            password : "请输入密码!"
        },
        submitHandler : loginHandler
    });

    function loginHandler()
    {
        var account = $("#account").val();
        var password = $("#password").val();
        var enPassword = RSAUtils.encryptedString(window.key, password);

        $.ajax({
            url : basePath + "sso/login.sso?r=" + Math.random(),
            data : {
                account : account,
                password : enPassword
            },
            dataType : 'json',
            type : 'post',
            success : function (msg)
            {
                console.log(arguments);
                var code = msg.code;

                switch(code)
                {
                    case -1:
                        Utils.showSuccess("登录成功!", function ()
                        {
                            var service = $("#service").val();
                            window.location.href = basePath + "sso/validate.sso?service=" + service;
                        });
                        break;
                    case 1:
                        Utils.showError("用户名或密码错误!");
                        break;
                    case 2:
                        Utils.showConfirm("已有相同账号登录,是否注销登录?", function ()
                        {
                            var tgt = msg.data;
                            invalidate(tgt, loginHandler);
                            $(this).dialog("close");
                        }, null);
                        break;
                }

            },
            error : function ()
            {
            }
        });
    }

    function invalidate(tgt, callback)
    {
        $.ajax({
            url : basePath + "sso/invalidate.sso",
            data : {tgt : tgt},
            dataType : 'json',
            type : 'post',
            success : function (result)
            {
                var msg = result.message;
                if (result.isError)
                {
                    Utils.showError(msg);
                }
                else
                {
                    callback();
                }
            },
            error : function ()
            {
                console.log(arguments);
            }

        });

    }

});